package com.gaogzhen.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author Administrator
 * @date 2022-12-05 09:51
 */
public class JdbcUtils {
    /**
     * c3p0数据库连接池对象属性
     */
    private static final ComboPooledDataSource ds = new ComboPooledDataSource();
    /**
     * 获取连接
     *  1. 直接从当前线程获取绑定的连接
     *  2. 如果连接对象为空
     *      2.1 在去连接池去获取连接
     *      2.2 将此对象绑定到当前线程
     */
    static ThreadLocal<Connection> tc = new ThreadLocal<>();

    /**
     * 获取数据库连接
     * @return  数据库连接
     * @throws SQLException sql异常
     */
    public static Connection getConnection() throws SQLException {
        Connection conn = tc.get();
        if (conn == null) {
            conn = ds.getConnection();
            tc.set(conn);
        }
        return conn;
    }

    /**
     * 提交事务并关闭连接
     * @param conn  连接
     */
    public static void commit(Connection conn) {
        try {
            if (conn != null) {
                conn.commit();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 回滚事务并关闭连接
     * @param conn  连接
     */
    public static void rollback(Connection conn) {
        try {
            if (conn != null) {
                conn.rollback();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接，释放资源
     * @param conn  连接
     */
    public static void close(AutoCloseable ...conn) {
        for (AutoCloseable closeable : conn) {
            if (closeable != null) {
                try {
                    closeable.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        tc.remove();
    }
}
